/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.im.bean.ImMsgBizEmployeeRecent;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.constants.WhoSend;
import com.yami.shop.im.dao.ImMsgBizEmployeeRecentMapper;
import com.yami.shop.im.service.ImMsgBizEmployeeRecentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author LZK
 * @date 2021-04-01 17:22:48
 */
@Service
@AllArgsConstructor
public class ImMsgBizEmployeeRecentServiceImpl extends ServiceImpl<ImMsgBizEmployeeRecentMapper, ImMsgBizEmployeeRecent> implements ImMsgBizEmployeeRecentService {

    private final ImMsgBizEmployeeRecentMapper imMsgBizEmployeeRecentMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateEmployeeRecent(ImMsgBizUserHistory imMsgBizUserHistory) {
        ImMsgBizEmployeeRecent imMsgBizEmployeeRecent = this.getOne(new LambdaQueryWrapper<ImMsgBizEmployeeRecent>()
                .eq(ImMsgBizEmployeeRecent::getSendType, imMsgBizUserHistory.getSendType())
                .eq(ImMsgBizEmployeeRecent::getBizId, imMsgBizUserHistory.getBizId())
                .eq(ImMsgBizEmployeeRecent::getEmployeeId, imMsgBizUserHistory.getEmployeeId())
                .eq(ImMsgBizEmployeeRecent::getUserId, imMsgBizUserHistory.getUserId()));
        if (Objects.isNull(imMsgBizEmployeeRecent)) {
            imMsgBizEmployeeRecent = new ImMsgBizEmployeeRecent();
            imMsgBizEmployeeRecent.setSendType(imMsgBizUserHistory.getSendType());
            imMsgBizEmployeeRecent.setBizId(imMsgBizUserHistory.getBizId());
            imMsgBizEmployeeRecent.setUserId(imMsgBizUserHistory.getUserId());
            imMsgBizEmployeeRecent.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
            imMsgBizEmployeeRecent.setEmployeeUnreadNum(0);
            imMsgBizEmployeeRecent.setStatus(imMsgBizUserHistory.getStatus());
            imMsgBizEmployeeRecent.setCreateTime(LocalDateTime.now());
            imMsgBizEmployeeRecent.setUpdateTime(LocalDateTime.now());
            this.save(imMsgBizEmployeeRecent);
        } else {
            if (Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.USER)) {
                imMsgBizEmployeeRecent.setEmployeeUnreadNum(imMsgBizEmployeeRecent.getEmployeeUnreadNum() + 1);
            }
            imMsgBizEmployeeRecent.setUpdateTime(LocalDateTime.now());
            this.updateById(imMsgBizEmployeeRecent);
        }
    }

}
